// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var mirroring = false;
var activeTab;
var windowId;

chrome.browserAction.onClicked.addListener(function(tab) {
  if (mirroring) {
    chrome.tabs.executeScript(activeTab, { code: 'stopMirroring();' });
    alert('stopMirroring')
    mirroring = false;
    activeTab = undefined;
    windowId = undefined;
  } else {
    mirroring = true;
    windowId = tab.windowId;
    mirrorTab(tab.id);
  }
});

function mirrorTab(tabId) {
  if (tabId == activeTab)
    return;

  if (activeTab)
    chrome.tabs.executeScript(activeTab, { code: 'stopMirroring();' });

  activeTab = tabId;

  chrome.tabs.executeScript(activeTab, { code: 'startMirroring();' });
}

chrome.tabs.onActiveChanged.addListener(function(tabId, selectInfo) {
  if (!mirroring)
    return;

  if (selectInfo.windowId != windowId)
    return;

  mirrorTab(tabId);
});

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if (!mirroring || sender.tab.id !== activeTab)
    sendResponse({ mirror: false });
  else
    sendResponse({ mirror: true });
});